﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using B.MESUI.Login.A_Public.Constants;
using B.MESUI.Login.A_Public.Helpers;

namespace B.MESUI.Login.A_Public.Helpers
{
    /// <summary>
    /// HTTP请求助手类
    /// </summary>
    public static class HttpClientHelper
    {
        private static readonly string _baseUrl = "http://39.103.49.30:9983"; // 可以从配置文件读取
        private static readonly string _projectLineBaseUrl = "http://39.103.49.30:9982";

        /// <summary>
        /// 发送GET请求，获取指定URL的响应内容。
        /// </summary>
        /// <param name="url">请求的完整URL</param>
        /// <returns>响应内容字符串</returns>
        public static async Task<string> GetAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(60);
                var response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new HttpRequestException($"GET请求失败: {response.StatusCode} - {errorContent}");
                }
            }
        }

        /// <summary>
        /// 发送POST请求，向指定URL提交数据。
        /// </summary>
        /// <param name="url">请求的完整URL</param>
        /// <param name="data">要提交的数据对象</param>
        /// <returns>响应内容字符串</returns>
        public static async Task<string> PostAsync(string url, object data)
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var jsonData = JsonConvert.SerializeObject(data);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
               
                try
                {
              
                    // ...后续处理
                    var response = await client.PostAsync(url, content);

                    if (response.IsSuccessStatusCode)
                    {
                        return await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        throw new HttpRequestException($"POST请求失败: {response.StatusCode} - {errorContent}");
                    }
                }
                catch (TaskCanceledException)
                {
                    XtraMessageBox.Show("请求超时，请稍后重试或联系管理员！", "超时", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }
            }
        }

        /// <summary>
        /// 发送PUT请求，向指定URL提交数据用于更新。
        /// </summary>
        /// <param name="url">请求的完整URL</param>
        /// <param name="data">要提交的数据对象</param>
        /// <returns>响应内容字符串</returns>
        public static async Task<string> PutAsync(string url, object data)
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var jsonData = JsonConvert.SerializeObject(data);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                var response = await client.PutAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new HttpRequestException($"PUT请求失败: {response.StatusCode} - {errorContent}");
                }
            }
        }

        /// <summary>
        /// 发送DELETE请求，删除指定URL的资源。
        /// </summary>
        /// <param name="url">请求的完整URL</param>
        /// <returns>响应内容字符串</returns>
        public static async Task<string> DeleteAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var response = await client.DeleteAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new HttpRequestException($"DELETE请求失败: {response.StatusCode} - {errorContent}");
                }
            }
        }

        /// <summary>
        /// 获取完整URL（拼接基础地址和端点）。
        /// </summary>
        /// <param name="baseUrl">基础地址</param>
        /// <param name="endpoint">接口端点</param>
        /// <returns>完整URL字符串</returns>
        public static string GetFullUrl(string baseUrl, string endpoint)
        {
            return $"{baseUrl.TrimEnd('/')}/{endpoint.TrimStart('/')}";
        }

        /// <summary>
        /// 获取工单API完整URL。
        /// </summary>
        /// <param name="endpoint">接口端点</param>
        /// <returns>完整URL字符串</returns>
        public static string GetWorkOrderUrl(string endpoint)
        {
            return GetFullUrl(_baseUrl, endpoint);
        }

        /// <summary>
        /// 获取产品锁定API完整URL。
        /// </summary>
        /// <param name="endpoint">接口端点</param>
        /// <returns>完整URL字符串</returns>
        public static string GetProductLockUrl(string endpoint)
        {
            return GetFullUrl(_baseUrl, endpoint);
        }

        /// <summary>
        /// 获取产线API完整URL。
        /// </summary>
        /// <param name="endpoint">接口端点</param>
        /// <returns>完整URL字符串</returns>
        public static string GetProjectLineUrl(string endpoint)
        {
            return GetFullUrl(_projectLineBaseUrl, endpoint);
        }

        /// <summary>
        /// 获取编码生成API完整URL。
        /// </summary>
        /// <param name="endpoint">接口端点</param>
        /// <returns>完整URL字符串</returns>
        public static string GetCodeGenUrl(string endpoint)
        {
            return GetFullUrl(_baseUrl, endpoint);
        }

        /// <summary>
        /// 构建查询参数字符串（如?a=1&b=2）。
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <returns>拼接好的查询字符串</returns>
        public static string BuildQueryString(Dictionary<string, object> parameters)
        {
            if (parameters == null || parameters.Count == 0)
                return string.Empty;

            var queryParams = new List<string>();
            foreach (var param in parameters)
            {
                if (param.Value != null)
                {
                    queryParams.Add($"{param.Key}={Uri.EscapeDataString(param.Value.ToString())}");
                }
            }
            return string.Join("&", queryParams);
        }
    }
}